<?php
namespace Common;

use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 创建oss
 * Class oss
 * @package app\index\controller
 */
class Oss
{
    protected $ossClient;
    protected $bucket;
    public function __construct()
    {
        $accessKeyId     = 'LTAI4hvvgRnFxkWJ';
        $accessKeySecret = 'Znv0WozVBmKzBbAU6R62p1824SyvEY';
        $endpoint        = 'oss-cn-shanghai.aliyuncs.com';
        $bucket = 'xhl';
        $this->bucket = $bucket;
        try {
            $ossClient       = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $this->ossClient = $ossClient;
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }

    /**
     * 指定文件目录 以及文件接收的file名
     * @param $dir
     * @param $name
     * @return bool
     */
    function uploadFile($dir, $name)
    {
        if (!isset($_FILES[$name])) {
            return false;
        }
        $file = $_FILES[$name];
        if (is_array($file['name'])) {
            $tmp   = [];
            $ext   = [];
            $count = count($file['name']);
            for ($i = 0; $i < $count; $i++) {
                if (empty($file['tmp_name'][$i]) || !is_file($file['tmp_name'][$i])) {
                    continue;
                }
                $ext[] = explode('.', $file['name'][$i])[1];
                $tmp[] = $file['tmp_name'][$i];
            }
        } else {
            $ext[] = explode('.', $file['name'])[1];
            $tmp[] = $file['tmp_name'];
        }
        $names = [];
        try {
            foreach ($tmp as $key => $tm) {
                $fileName = uniqid() . '.' . $ext[$key];
                $object   = $dir . '/' . $fileName;
                $this->ossClient->uploadFile($this->bucket, $object, $tmp[$key]);
                $names[]  = $object;
            }
            return $names;
        } catch (OssException $e){
            return FALSE;
        }
    }

    public function accepts()
    {
        $url = $this->uploadFile('index', 'img');
        var_dump($url);
    }

    /**
     * @return \think\response\View
     */
    public function formTest()
    {
        return view();
    }

    public function deleteFile($filePath)
    {
        return $this->ossClient->deleteObject($this->bucket,$filePath);
    }
}